package com.qf.sy2103.ssm.controller;

import com.qf.sy2103.ssm.constants.Constants;
import com.qf.sy2103.ssm.entity.User;
import com.qf.sy2103.ssm.service.UserServcie;
import com.qf.sy2103.ssm.vo.MessageVo;
import com.qf.sy2103.ssm.vo.PageVo;
import com.qf.sy2103.ssm.vo.TableVo;
import com.qf.sy2103.ssm.vo.UserVo;
import com.sun.deploy.net.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/user")
@Slf4j   // 相当于 public static Logger log = LoggerFactory.getLogger(UserController.class);
public class UserController {

//    public static Logger log = LoggerFactory.getLogger(UserController.class);


    @Autowired
    private UserServcie userServcie;

    // http://localhost:8080/user/get/1
    @RequestMapping("/get/{id}")
    @ResponseBody
    public User getUserById(@PathVariable("id") Integer id){
        String name = "jakc";
        log.info("方法参数为: {} {}",id,name);
//        System.out.println("UserController 方法getUserById 参数："+id);
        //1. 校验参数
        if(id<=0){
            return null;
        }
        //2. 调用service层
        final User user = userServcie.getUser(id);
        log.debug("返回值为:{}",user);
//        System.out.println("UserController 方法getUserById 返回值为："+user);
        return user;
    }


    // http://localhost:8080/user/login?name=jackma&password=123456&capchar=123456
    @RequestMapping("/login")
    @ResponseBody
    public MessageVo login(UserVo userVo, HttpSession session){
        log.debug("入参为：{}",userVo);

        // 校验参数
        final String capchar = userVo.getCapchar();

        // 从session中获取验证码
        final String captcha = (String) session.getAttribute("captcha");
        log.debug("session 中存放的验证码是：{}",capchar);

        if(capchar!=null&&capchar.equals(captcha)){  // 跟session中的验证码进行比对
            // 调用servcie层代码进行登录的业务逻辑处理
            Boolean result = userServcie.checkUserLogin(userVo);
            log.debug("userservcie返回的登录结果为:{}",result);
            // 进行响应
            if (result){ // 登录成功
                // 登录成功之后，需要把用户的相关信息写入session中。
                session.setAttribute(Constants.USER_LOGIN_SESSION_KEY,userVo);
                final MessageVo messageVo = new MessageVo(Constants.USER_CODE_LOGINSUCCESS, Constants.USER_MSG_LOGINSUCCESS, userVo);
                log.debug("返回消息为：{}",messageVo);
                return messageVo;
            }else { // 登录失败
                final MessageVo messageVo = new MessageVo(Constants.USER_CODE_LOGINFAIL, Constants.USER_MSG_LOGINFAIL, userVo);
                log.debug("返回消息为：{}",messageVo);
                return messageVo;
            }
        }

        // 验证码错误的响应
        final MessageVo messageVo = new MessageVo(Constants.USER_CODE_CHAPCHARERROR, Constants.USER_MSG_CHAPCHARERROR, null);
        log.debug("返回消息为：{}",messageVo);
        return messageVo;

    }


    @RequestMapping("/regist")
    @ResponseBody
    public MessageVo regist(UserVo userVo, MultipartFile source,HttpSession session ){
        log.debug("入参:{},{}",userVo,source);
        // 1. 参数校验

        // 2. 调用servcie层方法完成用户注册
        // 2.1 准备好存储头像的绝对路径
        final String realPath = session.getServletContext().getRealPath(Constants.FILE_UPLOAD_PATH);
        // 2.2 调用service
        Boolean result  =  userServcie.registUser(userVo,source,realPath);
        log.debug("userServcie 返回注册结果为：{}",result);
        // 3. 响应
        if (result){
            return MessageVo.ok(Constants.USER_CODE_RESIT_SUCCESS,Constants.USER_MSG_RESIT_SUCCESS,null);
        }else {
            return MessageVo.error(Constants.USER_CODE_RESIT_FAIL,Constants.USER_MSG_RESIT_FAIL,null);
        }


    }

//    http://localhost:8080/user/getAllUsers
    @RequestMapping("/getAllUsers")
    @ResponseBody
    public TableVo<User> getAllUsers(PageVo pageVo,User user){

        log.debug("入参:{}",pageVo);

//        TableVo<User> users = userServcie.getAllUsers(pageVo);

        TableVo<User> users = userServcie.getAllUsers(pageVo,user);


        log.debug("查到的数据为:{}",users);
        return users;

    }

    @RequestMapping("/current")
    @ResponseBody
    public User current(HttpSession session){
        // 从sessoion中获取当前登录用户的信息
        final UserVo userVo = (UserVo) session.getAttribute(Constants.USER_LOGIN_SESSION_KEY);
        final User dbuser = userVo.getDbuser();
        log.debug("当前登录用户信息为：{}",dbuser);
        return dbuser;
    }


    @RequestMapping("/pic")
    public void pic(String filename, HttpSession session, HttpServletResponse response) throws IOException {

        //获得要下载文件的绝对路径
        String path = session.getServletContext().getRealPath(Constants.FILE_UPLOAD_PATH);
        //文件的完整路径
        String real_path = path+"\\"+filename;

        log.debug("请求的图片名称为:{}",real_path);

        //读取目标文件，写出给客户端
        IOUtils.copy(new FileInputStream(real_path), response.getOutputStream());

    }

    @RequestMapping("/export")
    @ResponseBody
    public MessageVo export(HttpSession session) throws IOException {

        // 1. 调用service层的方法完成数据的全量导出，并且返回文件名
        final String realPath = session.getServletContext().getRealPath(Constants.FILE_UPLOAD_PATH);
//        String filename = userServcie.exportAllData(realPath);
        String filename = userServcie.exportAllDataBatch(realPath);
        // 2. 返回MessageVo

        return MessageVo.ok(Constants.USER_CODE_EXPORT_SUCCESS,Constants.USER_MSG_EXPORT_SUCCESS,filename);

    }

    @RequestMapping("/download")
    public void download(String filename, HttpSession session, HttpServletResponse response) throws IOException {

        //获得要下载文件的绝对路径
        String path = session.getServletContext().getRealPath(Constants.FILE_UPLOAD_PATH);
        //文件的完整路径
        String realFileName = path+"\\"+filename;

        log.debug("要下载的文件为：{}",realFileName);

        //设置响应头  告知浏览器，要以附件的形式保存内容   filename=浏览器显示的下载文件名
        response.setHeader("content-disposition","attachment;filename="+filename);

        //读取目标文件，写出给客户端
        IOUtils.copy(new FileInputStream(realFileName), response.getOutputStream());
    }

}
